<?php
/**
 * Display Vacation sheet
 * 
 * @author Xavier VILAIN
 */
use Fox\Grid\FieldCat\Field;
use Doctrine\DBAL\Types\Type;
use Hive\Vacation\Sheet;
use Fox\Dao\SqlFragment;
use Hive\Vacation\Holiday;

$idusr = User::current()->getId();

foreach($months as $key => $month)
{
	
	list($year,$month) = preg_split("/\/",$key);
	$currentDate = new DateTime("$year-$month-01");
	$holidaysGrid = array();
	
	// Load Holiday Information
	$finder = new Holiday();
	$holidays = $finder->find(new SqlFragment("year = ? AND month = ?",array($year,$month)));
	foreach($holidays as $holiday)
	{
		$holidaysGrid = array_merge($holidaysGrid,$holiday->toGrid());
	}
	
	// Build Empty Grid
	$grid = new Fox\Grid("vacations_".$year."_".$month);
	$grid->fieldcat(array("vacation_type","type"));
	while($currentDate <= $end_date)
	{
		$weeknb = $currentDate->format("w");
		$dateString = $currentDate->format("Y-m-d");
		if($weeknb == 0 || $weeknb == 1)
		{
			$color = "grey";
			$input = false;
		}
		elseif(in_array($dateString,$holidaysGrid))
		{
			$color = "orange";
			$input = false;
		}
		else
		{
			$color = "";
			$input = true;
		}
		$dayNb = $currentDate->format("d");
		$grid->fieldcat()->add(new Field("day",$dayNb."_am"))
						 ->input($input)
						 ->color($color);
		$grid->fieldcat()->add(new Field("day",$dayNb."_pm"))
						 ->input($input)
						 ->color($color);
		$gpField = new Field("day",$dayNb);
		$gpField->label($currentDate->format("D"));
		$grid->fieldcat()->buildSubTitleByGrouping(array($dayNb."_am",$dayNb."_pm"), $gpField);
		$currentDate->add(new DateInterval("P1D"));
	}
	
	// Prepare Initial Lines with only type labels
	foreach($types as $type)
	{
		$data[$type->getId()] = array();
	}
	
	// Load User Data
	$finder = new Sheet();
	$sheets = $finder->find(new SqlFragment("start_date >= ? AND end_date <= ? idusr = ?",array(
									$start_date,
									$end_date,
									$idusr
									),array(Type::DATE,Type::DATE,Type::INTEGER)),
									array("type" => false,"start_date" => false)
								);
	foreach($sheets as $sheet)
	{
		$line = $sheet->toGrid();
		$typeid = $sheet->type();
		if(!isset($data[$typeid]))
		{
			try {
				$type = new Hive\Vacation\Type($typeid);
				$data[$typeid] = array("label" => $type->label());
			}
			catch (Fox\Object\Exception\NotExist $e)
			{
				Fox\Message::Error("Type &1 not found");
				continue;
			}
		}
		$data[$typeid] = array_merge($data[$sheet->type()],$line);
	}
	$grids[] = $grid;
	unset($grid);
}